<template>
  <view class="login-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="navbar-content">
        <text class="navbar-title">账号管理</text>
      </view>
    </view>

    <!-- 登录表单 -->
    <view class="login-form">
      <!-- Logo和标题 -->
      <view class="header">
        <image class="logo" src="/static/images/logo.png" mode="aspectFit" />
        <text class="title">账号密码管理器</text>
        <text class="subtitle">安全便捷的多平台账号管理工具</text>
      </view>

      <!-- 登录方式切换 -->
      <view class="login-tabs">
        <view
          class="tab-item"
          :class="{ active: loginType === 'password' }"
          @click="switchLoginType('password')"
        >
          账号登录
        </view>
        <view
          class="tab-item"
          :class="{ active: loginType === 'oauth' }"
          @click="switchLoginType('oauth')"
        >
          快捷登录
        </view>
      </view>

      <!-- 账号密码登录 -->
      <view v-if="loginType === 'password'" class="password-login">
        <view class="input-group">
          <view class="input-label">用户名/手机号/邮箱</view>
          <input
            class="input-field"
            v-model="loginForm.login"
            placeholder="请输入用户名、手机号或邮箱"
            :maxlength="50"
          />
        </view>

        <view class="input-group">
          <view class="input-label">密码</view>
          <view class="password-input">
            <input
              class="input-field"
              v-model="loginForm.password"
              :password="!showPassword"
              placeholder="请输入密码"
              :maxlength="50"
            />
            <text
              class="password-toggle"
              @click="togglePassword"
            >
              {{ showPassword ? '隐藏' : '显示' }}
            </text>
          </view>
        </view>

        <button
          class="login-btn"
          :disabled="!canLogin || isLoading"
          @click="handlePasswordLogin"
        >
          {{ isLoading ? '登录中...' : '登录' }}
        </button>

        <view class="actions">
          <text class="link" @click="goToRegister">立即注册</text>
        </view>
      </view>

      <!-- 第三方登录 -->
      <view v-if="loginType === 'oauth'" class="oauth-login">
        <login-buttons @login="handleOAuthLogin" />

        <view class="oauth-tip">
          <text>首次使用将自动创建账号</text>
        </view>
      </view>

      <!-- 生物识别登录 -->
      <view v-if="showBiometric" class="biometric-login">
        <view class="divider">
          <text>或</text>
        </view>

        <button
          class="biometric-btn"
          @click="handleBiometricLogin"
        >
          <text class="icon">🔐</text>
          <text>生物识别登录</text>
        </button>
      </view>
    </view>

    <!-- 底部信息 -->
    <view class="footer">
      <text class="version">v{{ appVersion }}</text>
      <view class="links">
        <text class="link" @click="showPrivacy">隐私政策</text>
        <text class="separator">|</text>
        <text class="link" @click="showTerms">使用条款</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useUserStore, useAppStore } from '@/store'
import { wechatLogin, alipayLogin, douyinLogin, biometricAuth } from '@/utils/oauth'
import { handleError, showSuccess, navigateTo } from '@/utils/common'
import LoginButtons from '@/components/login-buttons/index.vue'

// Store
const userStore = useUserStore()
const appStore = useAppStore()

// 响应式数据
const loginType = ref<'password' | 'oauth'>('password')
const showPassword = ref(false)
const isLoading = ref(false)
const statusBarHeight = ref(0)

// 登录表单
const loginForm = ref({
  login: '',
  password: ''
})

// 计算属性
const canLogin = computed(() => {
  return loginForm.value.login.trim() && loginForm.value.password.trim()
})

const showBiometric = computed(() => {
  return appStore.enableBiometric && appStore.platformInfo.platform !== 'h5'
})

const appVersion = computed(() => {
  return appStore.appInfo?.app_version || '1.0.0'
})

// 页面加载
onMounted(() => {
  // 获取状态栏高度
  const systemInfo = uni.getSystemInfoSync()
  statusBarHeight.value = systemInfo.statusBarHeight || 0

  // 检查是否已登录
  if (userStore.isLoggedIn) {
    navigateToHome()
  }
})

// 切换登录方式
const switchLoginType = (type: 'password' | 'oauth') => {
  loginType.value = type
}

// 切换密码显示
const togglePassword = () => {
  showPassword.value = !showPassword.value
}

// 账号密码登录
const handlePasswordLogin = async () => {
  try {
    isLoading.value = true

    await userStore.login(loginForm.value)

    showSuccess('登录成功')
    navigateToHome()

  } catch (error) {
    handleError(error, '登录失败')
  } finally {
    isLoading.value = false
  }
}

// 第三方登录
const handleOAuthLogin = async (platform: string) => {
  try {
    isLoading.value = true

    switch (platform) {
      case 'wechat':
        const wechatResult = await wechatLogin()
        await userStore.wechatLogin(wechatResult.code, wechatResult.userInfo)
        break

      case 'alipay':
        const alipayResult = await alipayLogin()
        await userStore.alipayLogin(alipayResult.authCode)
        break

      case 'douyin':
        const douyinResult = await douyinLogin()
        await userStore.douyinLogin(douyinResult.code)
        break

      default:
        throw new Error('不支持的登录方式')
    }

    showSuccess('登录成功')
    navigateToHome()

  } catch (error) {
    handleError(error, '登录失败')
  } finally {
    isLoading.value = false
  }
}

// 生物识别登录
const handleBiometricLogin = async () => {
  try {
    const result = await biometricAuth()
    if (result) {
      // 生物识别成功，检查是否有缓存的登录信息
      const cachedToken = uni.getStorageSync('token')
      if (cachedToken) {
        await userStore.refreshToken()
        showSuccess('登录成功')
        navigateToHome()
      } else {
        uni.showToast({
          title: '请先使用其他方式登录',
          icon: 'none'
        })
      }
    }
  } catch (error) {
    handleError(error, '生物识别失败')
  }
}

// 前往注册页
const goToRegister = () => {
  navigateTo('/pages/login/register')
}

// 前往首页
const navigateToHome = () => {
  uni.reLaunch({
    url: '/pages/home/index'
  })
}

// 显示隐私政策
const showPrivacy = () => {
  // 实现显示隐私政策
  uni.showModal({
    title: '隐私政策',
    content: '我们重视您的隐私，所有数据都经过加密存储...',
    showCancel: false
  })
}

// 显示使用条款
const showTerms = () => {
  // 实现显示使用条款
  uni.showModal({
    title: '使用条款',
    content: '使用本应用即表示您同意我们的服务条款...',
    showCancel: false
  })
}
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
}

.custom-navbar {
  background: transparent;

  .navbar-content {
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: center;

    .navbar-title {
      font-size: 18px;
      font-weight: 600;
      color: white;
    }
  }
}

.login-form {
  flex: 1;
  padding: 40px 24px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.header {
  text-align: center;
  margin-bottom: 40px;

  .logo {
    width: 80px;
    height: 80px;
    margin-bottom: 16px;
  }

  .title {
    display: block;
    font-size: 24px;
    font-weight: 600;
    color: white;
    margin-bottom: 8px;
  }

  .subtitle {
    display: block;
    font-size: 14px;
    color: rgba(255, 255, 255, 0.8);
  }
}

.login-tabs {
  display: flex;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  margin-bottom: 32px;
  padding: 4px;

  .tab-item {
    flex: 1;
    text-align: center;
    padding: 12px;
    border-radius: 6px;
    color: rgba(255, 255, 255, 0.8);
    font-size: 16px;
    transition: all 0.3s;

    &.active {
      background: white;
      color: #333;
    }
  }
}

.password-login,
.oauth-login {
  .input-group {
    margin-bottom: 20px;

    .input-label {
      font-size: 14px;
      color: white;
      margin-bottom: 8px;
    }

    .input-field {
      width: 100%;
      padding: 16px;
      background: rgba(255, 255, 255, 0.9);
      border: none;
      border-radius: 8px;
      font-size: 16px;
      color: #333;

      &::placeholder {
        color: #999;
      }
    }

    .password-input {
      position: relative;

      .password-toggle {
        position: absolute;
        right: 16px;
        top: 50%;
        transform: translateY(-50%);
        color: #666;
        font-size: 14px;
        z-index: 1;
      }
    }
  }

  .login-btn {
    width: 100%;
    padding: 16px;
    background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
    color: white;
    border: none;
    border-radius: 8px;
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 20px;

    &:disabled {
      opacity: 0.6;
    }
  }

  .actions {
    text-align: center;

    .link {
      color: white;
      font-size: 14px;
      text-decoration: underline;
    }
  }
}

.oauth-login {
  .oauth-tip {
    text-align: center;
    margin-top: 20px;

    text {
      font-size: 12px;
      color: rgba(255, 255, 255, 0.8);
    }
  }
}

.biometric-login {
  margin-top: 24px;

  .divider {
    text-align: center;
    margin-bottom: 16px;

    text {
      color: rgba(255, 255, 255, 0.8);
      font-size: 14px;
    }
  }

  .biometric-btn {
    width: 100%;
    padding: 16px;
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.3);
    border-radius: 8px;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;

    .icon {
      font-size: 20px;
      margin-right: 8px;
    }
  }
}

.footer {
  padding: 24px;
  text-align: center;

  .version {
    display: block;
    color: rgba(255, 255, 255, 0.6);
    font-size: 12px;
    margin-bottom: 8px;
  }

  .links {
    .link {
      color: rgba(255, 255, 255, 0.8);
      font-size: 12px;
      text-decoration: underline;
    }

    .separator {
      color: rgba(255, 255, 255, 0.6);
      margin: 0 8px;
    }
  }
}
</style>